<?php

namespace App\Http\Controllers;

use App\B2BProject\Area;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class AreaGetterController extends Controller
{
    public function validate(Request $request, array $rules = null, array $messages = [], array $customAttributes = [])
    {
        parent::validate($request, ['code' => 'required|numeric']);
    }

    public static function jsonDataProvince(){
        $provinces = Area::where('parent_id', 0)->get();

        $data = [];

        foreach ($provinces as $province) {
            $data[] = ['code' => $province->id, 'text' => $province->name];
        }
        return json_encode($data);
    }

    public function getProvince()
    {
        $provinces = Area::where('parent_id', 0)->get();

        $data = [];

        foreach ($provinces as $province) {
            $data['data'][] = ['code' => $province->id, 'text' => $province->name];
        }

        return response()->json($data);
    }

    public function postCity(Request $request)
    {
        $this->validate($request);

        $data = [];
        foreach (Area::where('id', $request->input('code'))->where('level', 1)->firstOrFail()->children as $city) {
            $data['data'][] = ['code' => $city->id, 'text' => $city->name];
        }
        return response()->json($data);
     }

    public function postCounty(Request $request)
    {
        $this->validate($request);

        $data = [];

        foreach (Area::where('id', $request->input('code'))->where('level', 2)->firstOrFail()->children as $county) {
            $data['data'][] = ['code' => $county->id, 'text' => $county->name];
        }
        return response()->json($data);

    }
}
